<template>
  <div class="statistics-container">
    <h1>传承人统计</h1>
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import config from "../../config.js"
const chartRef = ref(null)
let chart = null
const fetchData = async () => {
  try {
    // 获取传承人数据
    const response = await fetch(config.API_HOST+'/artist/heritage_artists')
    const artistsData = await response.json()
    
    // 统计每个子分类的传承人数量
    const subCategoryCount = {}
    artistsData.forEach(artist => {
      const subCategory = artist.sub_category || '未分类'
      subCategoryCount[subCategory] = (subCategoryCount[subCategory] || 0) + 1
    })

    // 准备图表数据
    const subCategories = Object.keys(subCategoryCount)
    const values = Object.values(subCategoryCount)

    // 配置图表选项
    const option = {
      title: {
        text: '传承人分类统计',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: '{b}: {c} 人'
      },
      xAxis: {
        type: 'category',
        data: subCategories,
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '传承人数量'
      },
      series: [
        {
          name: '传承人数量',
          type: 'bar',
          data: values,
          itemStyle: {
            color: '#409EFF'
          }
        }
      ]
    }

    // 设置图表配置
    chart.setOption(option)
  } catch (error) {
    console.error('获取数据失败：', error)
  }
}

onMounted(() => {
  // 初始化图表
  chart = echarts.init(chartRef.value)
  
  // 获取数据并渲染图表
  fetchData()

  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    chart.resize()
  })
})
</script>

<style scoped>
.statistics-container {
  padding: 20px;
}

.chart-container {
  width: 100%;
  height: 500px;
  margin-top: 20px;
}
</style>